package com.shop.mall.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shop.mall.common.Result;
import com.shop.mall.entity.*;
import com.shop.mall.service.*;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.math.BigDecimal;

/**
 * <p>
 * 支付 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private ProductService productService;
    @Autowired
    private PayService payService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;

    @PostMapping("/add")
    @Operation(summary = "添加支付")
    public Result<String> add(@RequestBody Pay pay) {
        String code = pay.getCode();
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(Order::getCode, code);
        Order order = orderService.getOne(qw);
        if (order == null) {
            throw new RuntimeException("未找到该笔订单");
        }
        BigDecimal payMoney = pay.getMoney();
        Integer uId = pay.getuId();
        User user = userService.getUserById(uId);
        if (user == null) {
            throw new RuntimeException("未找到用户");
        }
        BigDecimal money = user.getMoney(); //用户余额
        if (money.compareTo(payMoney) < 0) {
            throw new RuntimeException("用户余额不足");
        }
        boolean result = payService.save(pay);
        if (!result) {
            return Result.error("支付失败");
        }
        //更新用户余额，商家余额
        BigDecimal left = money.subtract(payMoney);
        user.setMoney( left);
        userService.updateById(user);
        Integer proId = order.getProId();
        Product product = productService.getById(proId);
        Integer adminId = product.getAdminId();
        Admin admin = adminService.getAdminById(adminId);
        BigDecimal addMoney = admin.getMoney().add(payMoney);
        admin.setMoney(addMoney);
        adminService.updateById(admin);

        return Result.success();
    }

    @GetMapping("/getByCode")
    @Operation(summary = "根据id查询支付信息")
    public Result<Pay> getById(@RequestParam String code) {
        LambdaQueryWrapper<Pay> qr = new LambdaQueryWrapper<>();
        qr.eq(Pay::getCode, code);
        Pay pay = payService.getOne(qr);
        if (pay == null) {
            return Result.error("获取支付信息失败");
        }
        return Result.success(pay);
    }

}
